package com.ksyun.seckill.controller.online;


import com.ksyun.seckill.constants.RedisKey;
import com.ksyun.seckill.entity.Campaign;
import com.ksyun.seckill.rest.RestResult;
import com.ksyun.seckill.service.CampaignService;
import com.ksyun.seckill.service.SkService;
import com.ksyun.seckill.util.BizUtils;
import com.ksyun.seckill.util.ConfuseIdUtil;
import com.ksyun.seckill.util.GenerateVerifyUtil;

import com.ksyun.seckill.util.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/online/sc")
public class ScController {

    @Autowired
    CampaignService campaignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    ///online/sc/getVerifyCode

    @Resource(name = "SeckillService")
    SkService skService;
    /**
     * 生成验证码图片
     *
     * @param httpServletResponse
     */
    @RequestMapping(value = "/getVerifyCode", method = RequestMethod.GET)
    public void getVerifyCode(HttpServletResponse httpServletResponse) {
        String verifyCode = BizUtils.generateVerifyCode();
        GenerateVerifyUtil.generateVerifyCode(httpServletResponse, verifyCode);
    }
//    http://120.92.208.55:8888/api/online/sc/getSecKillPath?campaignId=8ajMWe29yz&phone=15571747016&verifyCode=

    /**
     * 生成秒杀url路径
     *
     * @param campaignId
     * @param phone
     * @param verifyCode
     * @return
     */
    @RequestMapping(value = "/getSecKillPath", method = RequestMethod.GET)
    public RestResult getSecKillPath(@NotNull @RequestParam(value = "campaignId") String campaignId,
                                     @NotNull @RequestParam(value = "phone") String phone,
                                     @RequestParam(value = "verifyCode", required = false) Integer verifyCode) {
        /**
         * 思路：
         *  1、可以将接收到的campaignId和phone进行md5加密，将加密后的字符串存入到redis中，然后返回给用户
         *
         *  2、在真正进行秒杀业务前进行检查url是否正确
         *
         *  状态：
         *      1、只有上线的活动才能进行查询活动
         *      1:新建  2:已上线　3.已结束 4.永久下线
         *
         */
        //查询秒杀商品的信息
        try {
            String decrypt = ConfuseIdUtil.decrypt(campaignId);
            Long camId = Long.valueOf(decrypt);
            String targetPath = skService.generateSecKillPath(camId,
                    phone, "");
            return RestResult.success().data(targetPath);
        } catch (Exception e) {
            throw new ServiceException("生成秒杀url失败，"+e.getMessage());
        }

    }


    /**
     * 秒杀接口
     *
     * @param campaignId 混淆后的活动id
     * @param phone      手机号
     * @param path       秒杀路径（需校验）
     * @return
     */
    @RequestMapping(value = "{path}/doSecKill", method = RequestMethod.POST)
    public RestResult doSecKill(@NotNull @RequestParam("campaignId") String campaignId,
                                @NotNull @RequestParam("phone") String phone,
                                @NotNull @PathVariable("path") String path) {
        log.info("campaignId:{},phone:{},path:{}",campaignId,phone,path);
        try {
            String decrypt = ConfuseIdUtil.decrypt(campaignId);
            Long camId = Long.valueOf(decrypt);
            skService.secKill(camId,phone,path);
            return RestResult.success();
        } catch (Exception e) {
            throw new ServiceException("秒杀失败!"+e.getMessage());
        }
    }



}
